import plugins_request from "@/plugin/request.js";
let apiUpload = plugins_request.apiUpload;

let toPageLogin = function () {
  uni.navigateTo({
    url: "/pages/login/loginForm",
  });
};

/*
import util from '@/plugin/util.js'
	
util.handleUploadImage({
		count: 1,
		successCallback: (res) => {
			this.upload_image = res.data.path;
		}
	});

*/

//上传图片
let handleUploadImage = function (option = {}) {
  uni.chooseImage({
    count: option.count || 1,
    mediaType: ["image"], // 图片
    sizeType: ["original", "compressed"], // 可以指定是原图还是压缩图，默认二者都有
    sourceType: ["album", "camera"], // 从相册选择
    success: (res) => {
      console.warn("选择图片", res);
      // this.headerImage = res.tempFilePaths[0];
      // res.tempFilePaths.forEach(file => {
      // 	this.api_uploadImage(file);
      // })

      // let file = res.tempFilePaths[0];
      // api_upload(file).then(resUpload => {
      // 	if (option.successCallback) {
      // 		option.successCallback(resUpload)
      // 	}
      // });

      res.tempFilePaths.forEach((file) => {
        // apiUpload({
        // 	url: '/upload',
        // 	method: 'post',
        // 	data: {
        // 		// action: 'index_localUpload', //login
        // 		file: file,
        // 		// if_touxiang: 1
        // 	},
        // }).then(res => {
        // 	if (res.code == 200) {
        // 		// this.edit_avatar_nick(res.data.path);
        // 		option.successCallback(res)
        // 	}
        // });

        apiUpload({
          url: "/upload",
          method: "post",
          data: {
            // action: "index_localUpload",
            file,
            // if_touxiang: 1,
            // ...option.data,
          },
        }).then((res) => {
          if (res.code == 200) {
            // this.edit_avatar_nick(res.data.path);
            option.successCallback(res);
          }
        });
        // api_upload(file).then(resUpload => {
        // 	if (option.successCallback) {
        // 		option.successCallback(resUpload)
        // 	}
        // });
      });
    },
  });
};

/*
import util from '@/plugin/util.js'
	
util.formatMillisecondsToDate(ms);

*/

//格式化日期
let formatMillisecondsToDate = function (milliseconds) {
  if (!milliseconds) {
    milliseconds = new Date().getTime();
  }
  // 创建一个Date对象
  var date = new Date(milliseconds);

  // 获取年、月、日
  var year = date.getFullYear();
  var month = ("0" + (date.getMonth() + 1)).slice(-2); // 月份是从0开始的，所以需要+1，并且使用slice保证始终是两位数
  var day = ("0" + date.getDate()).slice(-2); // 使用slice保证始终是两位数

  // 拼接日期字符串
  var formattedDate = year + "-" + month + "-" + day;

  return formattedDate;
};

//格式化日期
let formatMillisecondsToDateTime = function (milliseconds) {
  if (!milliseconds) {
    milliseconds = new Date().getTime();
  }
  // 创建一个Date对象
  var date = new Date(milliseconds);

  // 获取年、月、日
  var year = date.getFullYear();
  var month = ("0" + (date.getMonth() + 1)).slice(-2); // 月份是从0开始的，所以需要+1，并且使用slice保证始终是两位数
  var day = ("0" + date.getDate()).slice(-2); // 使用slice保证始终是两位数

  var hour = ("0" + date.getHours()).slice(-2); // 使用slice保证始终是两位数
  var minute = ("0" + date.getMinutes()).slice(-2); // 使用slice保证始终是两位数
  var second = ("0" + date.getSeconds()).slice(-2); // 使用slice保证始终是两位数

  // 拼接日期字符串
  var formattedDate =
    year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;

  return formattedDate;
};

let isValidMobile = function (mobile) {
  return /^1[3-9]\d{9}$/.test(mobile);
};

let isValidIdCard = function (idCard) {
  // 身份证号码为15位或者18位
  if (idCard.length !== 15 && idCard.length !== 18) {
    return false;
  }

  // 使用正则表达式匹配身份证号码的格式
  const regex = /^(\d{6})(\d{8})(\d{4})?$/;
  const match = idCard.match(regex);
  if (!match) {
    return false;
  }

  // 提取出生年月日
  const birthYear = match[1].substr(6, 4);
  const birthMonth = match[2].substr(0, 2);
  const birthDay = match[2].substr(2, 2);

  // 校验出生日期是否合法
  const birthDate = new Date(
    birthYear,
    parseInt(birthMonth, 10) - 1,
    parseInt(birthDay, 10)
  );
  if (isNaN(birthDate.getTime())) {
    return false;
  }

  // 如果是18位身份证，校验最后一位校验码
  if (idCard.length === 18) {
    const weightFactors = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
    const checkCodes = ["1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"];
    let sum = 0;
    for (let i = 0; i < 17; i++) {
      sum += idCard.charAt(i) * weightFactors[i];
    }
    const index = sum % 11;
    if (idCard.charAt(17).toUpperCase() !== checkCodes[index]) {
      return false;
    }
  }

  // 如果到这里都没有返回false，则身份证号有效
  return true;
};

let getAgeByIdCard = function (idCard) {
  // 提取出生日期
  const birthDateStr = idCard.substr(6, 8);
  const year = parseInt(birthDateStr.substr(0, 4), 10);
  const month = parseInt(birthDateStr.substr(4, 2), 10) - 1; // 月份要减1，因为JavaScript的月份是从0开始的
  const day = parseInt(birthDateStr.substr(6, 2), 10);

  // 创建出生日期对象
  const birthDate = new Date(year, month, day);

  // 创建当前日期对象
  const today = new Date();

  // 计算年龄
  let age = today.getFullYear() - birthDate.getFullYear();
  const m = today.getMonth() - birthDate.getMonth();
  if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
    age--;
  }

  return age;
};

/**
 * @param {Object} data
 * 复制接口返回的新数据 并置空所有值  解决详情页  undefined 问题
 */
let cloneDataAndEmptyValue = function (data) {
  var data_old = data;
  var data_new = {};
  for (var key in data_old) {
    var value_old = data_old[key];
    var value_new = "";
    if (typeof value_old == "string") {
      value_new = "";
    } else if (typeof value_old == "object") {
      if (Array.isArray(value_old)) {
        value_new = [];
      } else {
        value_new = {};
      }
    }
    data_new[key] = value_new;
  }
  console.warn(JSON.stringify(data_new));
};

let timeFormat = function (date, str = "年月日") {
  function padZero(num) {
    return num < 10 ? "0" + num : num;
  }

  var year = date.getFullYear();
  var month = padZero(date.getMonth() + 1); // 月份是从0开始的
  var day = padZero(date.getDate());
  var hours = padZero(date.getHours());
  var minutes = padZero(date.getMinutes());
  var seconds = padZero(date.getSeconds());

	return `${year}${str.slice(0,1)}${month}${str.slice(1,2)}${day}${str.slice(2,3)}`
}
const addCom = function(arg1, arg2, d) {
	arg1 = arg1.toString(), arg2 = arg2.toString();
	var arg1Arr = arg1.split("."),
		arg2Arr = arg2.split("."),
		d1 = arg1Arr.length == 2 ? arg1Arr[1] : "",
		d2 = arg2Arr.length == 2 ? arg2Arr[1] : "";
	var maxLen = Math.max(d1.length, d2.length);
	var m = Math.pow(10, maxLen);
	var result = Number(((arg1 * m + arg2 * m) / m).toFixed(maxLen));
	var d = arguments[2];
	return typeof d === "number" ? Number((result).toFixed(d)) : result;
}
// 两个数之间相减
const reduceCom = function(arg1, arg2) {
	var r1, r2, m, n;
	try {
		r1 = arg1.toString().split(".")[1].length
	} catch (e) {
		r1 = 0
	};
	try {
		r2 = arg2.toString().split(".")[1].length
	} catch (e) {
		r2 = 0
	};
	m = Math.pow(10, Math.max(r1, r2));
	// 动态控制精度长度
	n = (r1 >= r2) ? r1 : r2;
	return ((arg1 * m - arg2 * m) / m).toFixed(n);
}
//两个数乘法，精准计算
const accMul = function(arg1, arg2) {
	var m = 0,
		s1 = arg1.toString(),
		s2 = arg2.toString();
	try {
		m += s1.split(".")[1].length
	} catch (e) {};
	try {
		m += s2.split(".")[1].length
	} catch (e) {};
	return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
}
// 除法
const div = (arg1, arg2) => {
	if (!arg1) return '';
	if (!arg2) return '';
	var t1 = 0,
		t2 = 0,
		r1, r2;
	try {
		t1 = arg1.toString().split(".")[1].length
	} catch (e) {}
	try {
		t2 = arg2.toString().split(".")[1].length
	} catch (e) {}
	r1 = Number(arg1.toString().replace(".", ""));
	r2 = Number(arg2.toString().replace(".", ""));
	return (r1 / r2) * Math.pow(10, t2 - t1);
}
export default {
	toPageLogin,
	handleUploadImage,
	formatMillisecondsToDate,
	formatMillisecondsToDateTime,
	isValidMobile,
	isValidIdCard,
	getAgeByIdCard,
	timeFormat,
	div
};
